<template>
  <div class="box">
    <!-- 聊天信息 -->
    <div class="left">
      <div style="margin-top: 5px; margin-left: 15px">
        <span class="el-icon-s-comment" style="font-size: 22px"></span>
        <span>聊天列表</span>
      </div>
      <div style="margin-top: 10px">
        <el-input placeholder="输入用户账户id" style="width: 95%" />
      </div>
      <div style="height: 580px; overflow-y: scroll; background-color: #fff; margin-top: 10px; width: 95%; margin-left: 3px">
        <div
          v-for="(item, index) in messageList"
          :key="item.userId"
          :class="['item', item.userId === '0' ? 'active' : '', index === selectIndex ? 'active' : '']"
          @click="selectConnect(index)"
        >
          <message-card :message="item" :user="userList[index]" />
        </div>
      </div>
    </div>
    <!-- 聊天内容 -->
    <div class="center">
      <div class="top">
        <div v-if="flag">
          <div style="color: black; background-color: #eee; font-size: 24px; height: 40px; line-height: 40px; text-align: center">
            {{ currentUser.username }}
          </div>
          <div ref="myDiv" class="connect">
            <div v-for="(item, index) in currentMessage.message" :key="index" :class="['message', item.status === 0 ? 'position' : '']">
              <div
                style="
                  overflow: auto;
                  overflow-wrap: break-word;
                  max-width: 320px;
                  background-color: #b9dcff;
                  padding: 10px;
                  margin-bottom: 10px;
                  border-radius: 10px;
                "
              >
                <span v-if="item.type === 0">{{ item.content }}</span>
                <img v-else-if="item.type === 2" :src="item.content" style="width: 100%" />
              </div>
            </div>
          </div>
        </div>
        <div v-else style="position: absolute; left: 37%; top: 55%; font-size: 16px">您尚未选择联系人</div>
      </div>
      <div v-if="flag" class="buttom">
        <el-popover placement="top-start" trigger="click" width="300">
          <div>
            <picker
              :include="['people', 'Smileys']"
              :show-categories="false"
              :show-preview="false"
              :show-search="false"
              style="height: 200px; width: 300px"
              @select="addEmoji"
            />
          </div>
          <el-tooltip
            slot="reference"
            content="表情"
            effect="dark"
            placement="bottom"
            style="cursor: pointer; position: relative; top: 10px"
          >
            <span class="el-icon-star-off" style="color: #999; font-size: 22px"></span>
          </el-tooltip>
        </el-popover>

        <el-upload
          action="/api/v1/admin/message/uploadImgMessage"
          :before-upload="beforeImgUpload"
          :on-success="imguploadSuccess"
          :show-file-list="false"
          style="display: inline-block"
        >
          <el-tooltip content="图片" effect="dark" placement="bottom" style="cursor: pointer; position: relative; top: 10px">
            <span class="el-icon-picture-outline" style="color: #999; font-size: 22px; margin-left: 15px"></span>
          </el-tooltip>
        </el-upload>

        <el-tooltip content="截图" effect="dark" placement="bottom" style="cursor: pointer; position: relative; top: 10px">
          <span class="el-icon-scissors" style="color: #999; font-size: 22px; margin-left: 15px" @click="btnClick"></span>
        </el-tooltip>
        <el-button round style="position: relative; left: 490px; top: 8px" type="primary" @click="sendMessage">发送</el-button>
        <div>
          <el-input v-model="inputValue" placeholder="请输入消息，点击发送按钮发送" :rows="6" style="margin-top: 18px" type="textarea" />
        </div>
      </div>
    </div>
    <!-- 实用工具 -->
    <div class="right">
      <div v-if="flag && flag_draft">
        <el-descriptions :column="1" style="margin-top: 15px; margin-left: 10px; height: 200px" title="用户信息">
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="创建天数">{{ currentUser.createTime | getTime }}</el-descriptions-item>
          <el-descriptions-item label="是否企业认证">{{ currentUser.authentication === '1' ? '已认证' : '未认证' }}</el-descriptions-item>
          <el-descriptions-item label="公司名称">{{ currentUser.companyName }}</el-descriptions-item>
          <el-descriptions-item label="公司职位">{{ currentUser.duties }}</el-descriptions-item>
        </el-descriptions>
        <hr />
        <div style="font-weight: 900; margin: 10px">用户待审核数据</div>
        <div style="height: 395px; overflow-y: scroll; padding: 10px">
          <posts-audit-card
            v-for="(item2, index2) in postsList"
            :key="index2"
            :data="item2"
            style="height: 60px; border-radius: 0; margin-bottom: 10px"
          />
          <company-audit-card
            v-for="(item3, index3) in companyList"
            :key="index3"
            :data="item3"
            style="height: 60px; border-radius: 0; margin-bottom: 10px"
          />
          <avatar-audit-card
            v-for="(item1, index1) in avatarList"
            :key="index1"
            :data="item1"
            style="height: 60px; border-radius: 0; margin-bottom: 10px"
          />
          <div style="height: 20px; text-align: center; color: #ccc">已经到底了</div>
        </div>
      </div>
      <div v-else style="position: absolute; left: 25%; top: 50%; font-size: 16px">您尚未选择联系人</div>
    </div>
  </div>
</template>
<script>
  import MessageCard from '@/components/MessageCard/index.vue'
  import http_message from '@/api/message/message.js'
  import AvatarAuditCard from '@/components/AuditCard/AvatarAuditCard.vue'
  import PostsAuditCard from '@/components/AuditCard/PostsAuditCard.vue'
  import CompanyAuditCard from '@/components/AuditCard/CompanyAuditCard.vue'
  import { Picker } from 'emoji-mart-vue' //引入组件
  import ScreenShort from 'js-web-screen-shot'
  import aes from '@/utils/aes.js'

  export default {
    name: 'Message',
    components: {
      MessageCard,
      AvatarAuditCard,
      PostsAuditCard,
      CompanyAuditCard,
      Picker,
    },
    filters: {
      getTime(time) {
        //计算使用的时间
        const today = new Date()
        const target = new Date(time?.split(' ')[0])
        const diff = today - target
        const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
        return Math.floor(diff / oneDay)
      },
    },
    data() {
      return {
        messageList: [], //消息列表
        userList: [], //用户消息列表
        currentMessage: {}, //当前聊天的会话
        currentUser: {}, //当前聊天的用户
        flag: false, //是否显示聊天对话框
        flag_draft: false, //草稿箱
        selectIndex: -1, //默认选中对话
        avatarList: [], //头像审核列表
        postsList: [], //职位审核列表
        companyList: [], //公司审核列表
        inputValue: '', //输入的内容
        centerDialogVisible: false, //截图是否显示
        // 截图数据
        uploadlist: [],
        imageFilelist: [],
        ws: null,
      }
    },
    mounted() {
      this.getMessageList()
      const user = this.getLocalUser()
      this.ws = new WebSocket(`ws://127.0.0.1:10011/api/v1/webSocket/${user.userNumber}`)

      this.ws.onmessage = this.websocket_message
    },
    methods: {
      // 监听服务器发送webSocket
      websocket_message(e) {
        const data = JSON.parse(aes.Decrypt(e.data))
        if (Object.keys(this.currentMessage).length === 0 || this.currentMessage.userId !== data.userId) {
          //表示未选择对话，或者不在当前对话的用户
          for (let i = 0; i < this.messageList.length; i++) {
            if (data.userId === this.messageList[i].userId) {
              this.messageList[i].message.push(data.messageItem)
              this.messageList[i].number = this.messageList[i].number + 1
              break
            }
          }
        } else {
          console.log(this.currentMessage.message.length)
          this.currentMessage.message.push(data.messageItem)
          console.log(this.currentMessage.message.length)
          this.increaseWidth()
          for (let i = 0; i < this.messageList.length; i++) {
            if (data.userId === this.messageList[i].userId) {
              this.messageList[i].message.push(data.messageItem)
              break
            }
          }
        }
      },
      // 获得local存储的用户
      getLocalUser() {
        const user = JSON.parse(localStorage.getItem('userInfo'))
        return user
      },
      // 获得消息列表
      async getMessageList() {
        const userNumber = this.getLocalUser().userNumber
        const result = await http_message.getMessage(userNumber)
        if (result.code === 200) {
          // 排序按照最后一条短息时间先后
          const firstElement = result.data.connect[0]
          this.messageList = result.data.connect
            .slice(1)
            .sort((a, b) => new Date(b.message[b.message.length - 1].time) - new Date(a.message[a.message.length - 1].time))
          this.messageList.unshift(firstElement)
          this.getUserList()
        }
      },
      // 获得聊天用户信息
      async getUserList() {
        for (let i = 0; i < this.messageList.length; i++) {
          const result = await http_message.getUserInfo(this.messageList[i].userId)
          if (result.code === 200) {
            if (result.data === '草稿箱') {
              result.data = {
                username: '草稿箱',
                userId: '0',
                avatarImage: 'http://121.40.171.110:9000/client-avatar/avatar-draft.png',
              }
            }
            this.userList.push(result.data)
          }
        }
      },
      // 选择聊天会话
      selectConnect(index) {
        this.flag = true
        this.selectIndex = index
        this.messageList[index].number = 0
        this.currentMessage = this.messageList[index]
        this.currentUser = this.userList[index]
        this.increaseWidth()
        if (index !== 0) {
          this.getAuditInfo(this.currentUser.userId)
          this.flag_draft = true
        } else {
          this.flag_draft = false
        }
        // 后端发送请求清除number
        http_message.clearNumber(this.currentUser.userId)
      },
      // 获得当前用户未审核数据
      async getAuditInfo(userId) {
        const result = await http_message.getAuditInfo(userId)
        if (result.code === 200) {
          this.avatarList = result.data.avatar
          this.postsList = result.data.posts
          this.companyList = result.data.company
        }
      },
      // 添加表情包
      addEmoji(e) {
        this.inputValue += e.native
      },
      // 发送消息
      sendMessage() {
        if (this.inputValue !== '') {
          const data = {
            content: this.inputValue,
            status: 0,
            time: new Date()
              .toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
              })
              .replace(/\//g, '-'),
            type: 0,
          }
          this.inputValue = ''
          this.currentMessage.message.push(data)
          this.increaseWidth()
          this.userCardToTop(this.currentUser.userId)
          // 后端发送网络请求
          http_message.sendMessage(this.currentUser.userId, data)
        }
      },
      // 回到消息底部
      increaseWidth() {
        this.$nextTick(() => {
          // 使用nextTick确保DOM更新后执行滚动操作
          setTimeout(() => {
            const myDiv = this.$refs.myDiv
            myDiv.scrollTop = myDiv.scrollHeight
          }, 200)
        })
      },
      // 发送图片函数
      beforeImgUpload(rawFile) {
        if (!(rawFile.type === 'image/jpeg' || rawFile.type === 'image/png')) {
          this.$message.error('图片必须是jpg或者png格式')
          return false
        } else if (rawFile.size / 1024 / 1024 > 10) {
          this.$message.error('图片必须小于10MB')
          return false
        }
        return true
      },
      // 上传图片成功
      imguploadSuccess(response) {
        if (response.code === 200) {
          const data = {
            content: response.data,
            status: 0,
            type: 2,
            time: new Date()
              .toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
              })
              .replace(/\//g, '-'),
          }
          this.currentMessage.message.push(data)
          this.increaseWidth()
          // 后端发送请求保存
          http_message.sendMessage(this.currentUser.userId, data)
          this.userCardToTop(this.currentUser.userId)
        } else {
          this.$message.error('图片上传失败')
        }
      },
      // 用户头像回到顶层
      userCardToTop(userId) {
        //userId:和那个用户聊天的id
        if (userId === '0') {
          return
        }
        let index = 1
        for (let i = 1; i < this.userList.length; i++) {
          if (this.userList[i].userId === userId) {
            index = i
            break
          }
        }
        if (index !== 1) {
          this.selectIndex = 1
          const data1 = this.userList[index]
          this.userList.splice(index, 1)
          this.userList.splice(1, 0, data1)

          const data2 = this.messageList[index]
          this.messageList.splice(index, 1)
          this.messageList.splice(1, 0, data2)

          // 整理MessageData数据
          // for (let i = 0; i < this.userList.length; i++) {
          //   for (let j = 0; i < this.messageList.connect.length; j++) {
          //     if (this.userList[i].userId === this.messageList.connect[j].userId) {
          //       const data = this.messageList.connect[j]
          //       this.messageList.connect[j] = this.messageList.connect[i]
          //       this.messageList.connect[i] = data
          //     }
          //   }
          // }
        }
      },
      // 截图函数

      btnClick() {
        const screenShotHandler = new ScreenShort({
          enableWebRtc: false, //是否显示选项框
          level: 99, //层级级别
          completeCallback: this.callback,
          closeCallback: this.closeFn,
        })
      },

      async callback(base64data) {
        const result = await http_message.snedScreenshot(base64data)
        const data = {
          content: result.data,
          status: 0,
          type: 2,
          time: new Date()
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
            })
            .replace(/\//g, '-'),
        }
        this.currentMessage.message.push(data)
        this.increaseWidth()
        // 后端发送请求保存
        http_message.sendMessage(this.currentUser.userId, data)
        this.userCardToTop(this.currentUser.userId)
        if (result.code === 200) {
          this.$message({
            type: 'success',
            message: '截图取消成功',
          })
        }
      },
      closeFn() {
        this.$message({
          type: 'success',
          message: '截图取消成功',
        })
      },

      // 截图函数
    },
  }
</script>

<style lang="scss" scoped>
  .connect {
    height: 401px;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 10px;
    .message {
      display: flex;
      justify-content: flex-start;
    }
    .position {
      display: flex;
      justify-content: flex-end;
    }
  }
  .box {
    display: flex;
    width: 100%;
    height: 89vh;
    border-radius: 15px;
    overflow: hidden;
    .left {
      flex: 1;
      background-color: #f7f8fa;
      .item {
        height: 55px;
        margin-top: 2px;
        cursor: pointer;
      }
      .item:hover {
        background-color: #eee;
      }
      .active {
        background-color: #eee;
      }
    }
    .center {
      flex: 3;
      background-color: #f0f2f5;
      .top {
        height: 70%;
        position: relative;
      }
      .buttom {
        border-top: 1px solid #ccc;
        height: 30%;
        margin: 0 auto;
        width: 95%;
        padding-top: 5px;
      }
    }
    .right {
      flex: 1;
      background-color: #ffffff;
      position: relative;
    }
  }
</style>
